import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:wan_android_flutter/common/network/http_util.dart';
import 'package:wan_android_flutter/common/network/json_parse.dart';
import 'package:wan_android_flutter/common/network/model/banner_model.dart';

import '../../../common/base/base_controller.dart';
import '../../../common/network/model/categorys_model.dart';
import 'home_state.dart';

class HomeLogic extends BaseController {
  final HomeState state = HomeState();

  EasyRefreshController controller = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );

  @override
  Future<void> onLoadData() async {
    super.onLoadData();
    loadBanners();
    loadCategorys();
  }

  Future<void> loadBanners() async {
    final response = await httpUtil.get("/banner/json");
    if (response.statusCode == 200 && response.data is Map<String, dynamic>) {
      final bannerModel = JsonParse.fromJsonMap<BannerModel>(response.data);
      if (bannerModel?.data?.isNotEmpty == true) {
        state.banners.assignAll(bannerModel!.data!);
      }
    }
  }

  Future<void> loadCategorys() async {
    final response = await httpUtil.get("/article/list/${state.pageIndex}/json");
    if (response.statusCode == 200 && response.data is Map<String, dynamic>) {
      final categorysModel = JsonParse.fromJsonMap<CategorysModel>(response.data);
      if (categorysModel?.data?.datas?.isNotEmpty == true) {
        if (state.pageIndex == 0) {
          state.categoryList.assignAll(categorysModel!.data!.datas!);
        } else {
          state.categoryList.addAll(categorysModel!.data!.datas!);
        }
        state.categorys.assignAll(state.categoryList);
        controller.finishRefresh();
        controller.finishLoad();
      }
    }
  }

  @override
  void onDetached() {
    super.onDetached();
    controller.dispose();
  }
}
